package com.shuhua.taskServer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuhua.pojo.entity.Announcement;
import com.shuhua.taskServer.mapper.AnnouncementMapper;
import com.shuhua.taskServer.service.AnnouncementService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {
    @Override
    public Announcement getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<Announcement> searchByTitle(String title) {
        LambdaQueryWrapper<Announcement> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Announcement::getTitle, title);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<Announcement> filterByDate(String type) {
        LambdaQueryWrapper<Announcement> wrapper = new LambdaQueryWrapper<>();
        LocalDate now = LocalDate.now();
        Date start = null, end = null;

        switch (type) {
            case "today":
                start = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
                end = Date.from(now.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                break;
            case "week":
                LocalDate weekStart = now.minusDays(now.getDayOfWeek().getValue() - 1);
                start = Date.from(weekStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
                end = Date.from(now.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                break;
            case "month":
                LocalDate monthStart = now.withDayOfMonth(1);
                start = Date.from(monthStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
                end = Date.from(now.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                break;
            default:
                return baseMapper.selectList(null);
        }
        wrapper.ge(Announcement::getTime, start).lt(Announcement::getTime, end);
        return baseMapper.selectList(wrapper);
    }
}